<template>
    <div class="goods-sku">
        <dl v-for="item in goods.specs" :key="item.id">
            <dt>{{ item.name }}</dt>
            <dd>
                <template v-for="val in item.values" :key="val.item">
                    <!-- title 鼠标悬浮 显示文字 -->
                    <!-- 两种类别 一种图片 一种文字 -->
                    <img :class="{ selected: val.selected }" @click="clickSpecs(item, val)" v-if="val.picture"
                        :src="val.picture" :title="val.name" alt="">
                    <span :class="{ selected: val.selected }" @click="clickSpecs(item, val)" v-else>{{ val.name
                        }}</span>
                </template>
            </dd>
        </dl>
    </div>
</template>
<script>
import getPowerSet from '@/vender/power-set'
const spliter = '❤'
export default {
    name: 'GoodsSku',
    props: {
        goods: {
            type: Object,
            default: () => ({ specs: [], skus: [] })
        },
        skuId: {
            type: String,
            default: ' '
        }
    },
    setup(props, { emit }) {
        const pathMap = getPathMap(props.goods.skus)
        // 根据传入的skuId默认选中规格按钮
        initSelectedStatus(props.goods, props.skuId)
        // 组件初始化的时候更新禁用状态
        updateDisabledStatus(props.goods.specs, pathMap)


        const clickSpecs = (item, val) => {
            // 如果是禁用状态不作为
            if (val.disabled) return false
            // 点击选中 选中取消
            if (val.selected) {
                val.selected = false
            } else {//点击未选中 清除所有选中 然后选中点击元素
                item.values.forEach(bv => { bv.selected = false })
                val.selected = true
            }
            // 点击的时候更新禁用状态
            updateDisabledStatus(props.goods.specs, pathMap)
            // 得到当前选中规格集合 并去除undefined
            const selectedArr = getSelectedArr(props.goods.specs).filter(v => v)
            // 判断sku规格是否选全
            if (selectedArr.length === props.goods.specs.length) {
                // 从字典中搜索匹配的键值对
                const skuIds = pathMap[selectedArr.join(spliter)]
                // 用id 从skus中获取对应的数据
                const sku = props.goods.skus.find(sku => sku.id === skuIds[0])
                // 传递
                // console.log(sku)
                emit('change', {
                    skuId: sku.id,
                    price: sku.price,
                    oldPrice: sku.oldPrice,
                    inventory: sku.inventory,
                    // reduce() 方法对数组中的每个元素按序执行一个由你提供的 reducer 函数，每次运行都会 将先前元素的计算结果作为参数传入，最后将其结果 汇总为单个返回值
                    specsText: sku.specs.reduce((p, n) => `${p} ${n.name}：${n.valueName}`, ' ').replace(' ', ' ')
                })
            } else {
                emit('change', {})
            }
        }
        return { clickSpecs }
    }
}

// 利用power-set 列出排列组合所有结果 就是路径字典List
const getPathMap = (skus) => {
    const pathMap = {}
    skus.forEach(sku => {
        if (sku.inventory) {
            const specs = sku.specs.map(spec => spec.valueName)
            const powerSet = getPowerSet(specs)
            powerSet.forEach(set => {
                const key = set.join(spliter)
                if (pathMap[key]) {
                    pathMap[key].push(sku.id)
                } else {
                    pathMap[key] = [sku.id]
                }
            })

        }
    })
    return pathMap
}
// 得到当前选中规格集合
const getSelectedArr = (specs) => {
    const selectedArr = []
    specs.forEach(spec => {
        const selectedVal = spec.values.find(val => val.selected)
        selectedArr.push(selectedVal ? selectedVal.name : undefined)
    })
    return selectedArr
}
// 更新按钮的禁用状态
const updateDisabledStatus = (specs, pathMap) => {
    specs.forEach((spec, i) => {
        const selectedArr = getSelectedArr(specs)

        spec.values.forEach(val => {
            // 已经选中的按钮不用判断
            if (val.name === selectedArr[i]) return false
            // 未选中的替换对应的值
            selectedArr[i] = val.name
            // 过滤无效值得到key
            // selectedArr.filter(v => v) 去除nudefined null
            const key = selectedArr.filter(v => v).join(spliter)
            // 设置禁用状态
            val.disabled = !pathMap[key]
        })
    })
    // console.log(1)
}
// 初始化选中状态 通过传来的货号ID来 初始化匹配选中
const initSelectedStatus = (goods, skuId) => {
    const sku = goods.skus.find(sku => sku.id === skuId)
    if (sku) {
        goods.specs.forEach((spec, i) => {
            const value = sku.specs[i].valueName
            spec.values.forEach(val => {
                val.selected = val.name === value
            })
        })
    }
}
</script>
<style scoped lang="less">
.sku-state-mixin () {
    border: 1px solid #e4e4e4;
    margin-right: 10px;
    cursor: pointer;

    &.selected {
        border-color: @xtxColor;
    }

    &.disabled {
        opacity: 0.6;
        border-style: dashed;
        cursor: not-allowed;
    }
}

.goods-sku {
    padding-left: 10px;
    padding-top: 20px;

    dl {
        display: flex;
        padding-bottom: 20px;
        align-items: center;

        dt {
            width: 50px;
            color: #999;
        }

        dd {
            flex: 1;
            color: #666;

            >img {
                width: 50px;
                height: 50px;
                .sku-state-mixin ();
            }

            >span {
                display: inline-block;
                height: 30px;
                line-height: 28px;
                padding: 0 20px;
                .sku-state-mixin ();
            }
        }
    }
}
</style>